//
//  MYGCommunityManager.swift
//  MYGrow
//
//  Created by 林矗 on 2024/3/16.
//

import UIKit

class MYGCommunityManager {
    static let `shareManager` = MYGCommunityManager()
    private var communities: [MYGCommunityCommunityModel] = []
    var isFirstEnterCommunity: Bool {
        set {
            UserDefaults.standard.setValue(newValue, forKey: "isFirstEnterCommunity")
            UserDefaults.standard.synchronize()
        }
        get {
            UserDefaults.standard.value(forKey: "isFirstEnterCommunity") as? Bool ?? false
        }
    }
    
    func loadCommunities(completion: (()->())? = nil) {
        MMYGNetwork<MYGCommunityApi, MYGPageModel<MYGCommunityCommunityModel>>.request(target: MYGCommunityApi.comnunities) {[weak self] response in
            guard let response = response else { return }
            self?.communities = response.list
            completion?()
        } failed: { _, error in
            completion?()
        }
        
    }
    
    func getAllCommunities(completion: @escaping (([MYGCommunityCommunityModel]) -> ())) {
        if communities.count > 0 {
            completion(communities)
            loadCommunities{}
        } else {
            loadCommunities {[weak self] in
                completion(self?.communities ?? [])
            }
        }
    }
    
    func enterCommnity() {
        if !isFirstEnterCommunity {
            let vc = MYGCommunityRecommendController()
            UIViewController.currentViewController?.navigationController?.pushViewController(vc)
        } else {
            let vc = MYGAnswerViewViewController()
            UIViewController.currentViewController?.navigationController?.pushViewController(vc)
        }
    }
}
